package com.zhy.system.controller;

import com.zhy.common.helper.JwtHelper;
import com.zhy.common.result.Result;
import com.zhy.common.result.ResultCodeEnum;
import com.zhy.common.util.MD5;
import com.zhy.model.system.SysUser;
import com.zhy.model.vo.LoginVo;
import com.zhy.system.exception.YuanException;
import com.zhy.system.service.SysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * @author 随缘而愈
 * @version 1.0
 * @description 用户登录控制层
 * @date 11/3/2024 上午11:03
 */
@Api(tags = "处理前端登录")
@RestController
@RequestMapping("/admin/system/index")
public class IndexController {

    @Resource
    private SysUserService sysUserService;

    @ApiOperation(value = "登录")
    @PostMapping("/login")
    public Result login(@RequestBody LoginVo loginVo) {
        SysUser sysUser = sysUserService.getByUsername(loginVo.getUsername());
        if(null == sysUser) {
            throw new YuanException(ResultCodeEnum.ACCOUNT_ERROR);
        }
        if(!MD5.encrypt(loginVo.getPassword()).equals(sysUser.getPassword())) {
            throw new YuanException(ResultCodeEnum.PASSWORD_ERROR);
        }
        if(sysUser.getStatus().intValue() == 0) {
            throw new YuanException(ResultCodeEnum.ACCOUNT_STOP);
        }

        Map<String, Object> map = new HashMap<>();
        // TODO 信息存入redis中

        map.put("token", JwtHelper.createToken(sysUser.getId(), sysUser.getUsername()));
        return Result.ok(map);
    }

    @ApiOperation(value = "获取用户信息")
    @GetMapping("/info")
    public Result info(HttpServletRequest request) {
        Long userId = JwtHelper.getUserId(request.getHeader("token"));
        Map<String, Object> userInfo = sysUserService.getUserInfoByUserId(userId);
        return Result.ok(userInfo);
    }
}
